package com.rabbitmq.rabbitmq.service.impl;

import com.caicai.domain.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.rabbitmq.config.MutiplyMessageConfig;
import com.rabbitmq.rabbitmq.service.SendService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Component
public class SendServiceImpl  implements SendService,RabbitTemplate.ConfirmCallback {

	private CountDownLatch countDownLatch=new CountDownLatch(50);

	@Value("${mq.topicexchange.string}")
	private String  strExchange;

	@Autowired
	RabbitTemplate rabbitTemplate;
	@Override
	public void sendStr(String message) {

		for (int i=0;i<10;i++){
			int a=i;
			Thread thread=new Thread(
					//确认消息是否发送成功，实现confirm接口
					()->{
						try {
							//countDownLatch.countDown();
							//			try {
							//				countDownLatch.await();
							//			} catch (InterruptedException e) {
							//				e.printStackTrace();
							//			}
							rabbitTemplate.setConfirmCallback(this);
							Map map=new HashMap();
							map.put("key",a);
							CorrelationData correlationData = new CorrelationData(a+"");
							rabbitTemplate.convertAndSend(strExchange,"caicai-str-routingKey",map,correlationData);

						} catch (Exception e) {
							e.printStackTrace();
						}

					}

			);
			thread.start();

		}


	}




	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		if(ack){
			System.out.println("消息发送成功。。。。。。。");
		}else{
			System.out.println("消息发送失败。。。。。。。"+cause);
		}
	}

	//测试对象消息，改变解析器后对象传输有问题
	@Override
	public void sendUser(User user) {

		ObjectMapper mapper=new ObjectMapper();
		try {
			rabbitTemplate.convertAndSend(strExchange,"caicai-user-routingKey", mapper.writeValueAsString(user));
		} catch (JsonProcessingException e) {
			System.out.println(e);
		}
	}

	//测试多队列消息
	@Override
	public void sendMutiply() {
		rabbitTemplate.convertAndSend(MutiplyMessageConfig.mutiplyExchange,MutiplyMessageConfig.mutiplyKey,"消息");
	}

	@Override
	public void sendFaloutMessage() {
		rabbitTemplate.convertAndSend(MutiplyMessageConfig.mutiplyFanoutExchange,"","falout消息");

	}


}
